from mongoengine import Document, StringField, IntField, DateTimeField
from datetime import datetime

class User(Document):
    # 假设 openid 是唯一的
    openid = StringField(required=True, unique=True)
    nickname = StringField(required=True, max_length=50)
    level = IntField(min_value=1)
    score = IntField(default=0)
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)
    
    
    def save(self, *args, **kwargs):
        if not self.updated_at:  # 如果 updated_at 没有设置，则设置为创建时间
            self.updated_at = datetime.now()
        else:  # 否则更新为当前时间
            self.updated_at = datetime.now()
        super(User, self).save(*args, **kwargs)
        
    # 可以添加方法来表示业务逻辑，例如获取用户信息
    def get_user_info(self):
        return {
            "openid": self.openid,
            "nickname": self.nickname,
            "level": self.level,
            "score": self.score,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
        }
        
        
class UserCat(Document):
    # 假设 openid 是唯一的
    openid = StringField(required=True)  # 与User表的openid关联
    ar_type = StringField(required=True)  # 道具类型
    quantity = IntField(default=0)  # 道具数量
    created_at = DateTimeField(default=datetime.now)
    
    
    def save(self, *args, **kwargs):
        if not self.updated_at:  # 如果 updated_at 没有设置，则设置为创建时间
            self.updated_at = datetime.now()
        else:  # 否则更新为当前时间
            self.updated_at = datetime.now()
        super(User, self).save(*args, **kwargs)
        
        
class Cat(Document):
    avatar_id = IntField(primary_key=True)  # 每个小猫头像的唯一ID
    name = StringField(required=True)  # 小猫头像的名字
    description = StringField()  # 小猫头像的描述
    image_url = StringField()  # 小猫头像的图片URL
    unlock_condition = StringField()  # 解锁条件，例如“通关10次”
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)        